<template>
	<div class="account-form">
		<img class="logo" src="@/assets/logo/logo1.png" alt="logo" />
		<el-form
			ref="form"
			class="form"
			size="small"
			:model="form"
			:rules="rules"
			:disabled="saving"
			@submit.native.prevent
		>
			<transition name="fade-transform" mode="out-in">
				<div v-if="!isNext" key="prev">
					<el-form-item label="用户名" prop="mobile">
						<el-input
							prefix-icon="el-icon-user"
							placeholder="请输入用户名"
							v-model.trim="form.mobile"
							maxlength="11"
							auto-complete="off"
							@keyup.enter.native="submit"
						/>
					</el-form-item>
					<el-row :gutter="20" class="pt-1" v-if="!isNext">
						<el-col :span="isDingding ? 12 : 24">
							<el-button
								size="small"
								type="primary"
								class="submit-btn"
								@click="nextStep('nextStep')"
								:loading="saving"
								:disabled="!form.mobile"
							>
								下一步
							</el-button>
						</el-col>
						<el-col :span="12" v-if="isDingding">
							<el-button
								size="small"
								:loading="ddLoading"
								class="submit-btn"
								@click="dingdingLogin"
							>
								钉钉登录
							</el-button>
						</el-col>
					</el-row>
				</div>
				<div v-else key="next">
					<el-form-item label="集团" prop="user_id">
						<cl-select
							v-model="form.user_id"
							style="width: 100%"
							placeholder="请选择集团"
						>
							<icon-svg
								slot="prefix"
								name="icon-personnel"
								style="margin-left: 5px"
							/>
							<el-option
								v-for="item in groupList"
								:key="item.user_id"
								:label="item.name"
								:value="item.user_id"
							/>
						</cl-select>
					</el-form-item>
					<el-form-item label="密码" prop="password" v-if="!isPwdLogin">
						<el-input
							prefix-icon="el-icon-lock"
							type="password"
							placeholder="请输入密码"
							v-model.trim="form.password"
							maxlength="20"
							auto-complete="off"
							show-password
							@keyup.enter.native="submit"
						/>
					</el-form-item>
					<el-row :gutter="20" class="pt-1">
						<el-col :span="12">
							<el-button
								size="small"
								plain
								class="submit-btn"
								@click="
									() => {
										isNext = false;
										isPwdLogin = false;
									}
								"
								:disabled="saving"
							>
								上一步
							</el-button>
						</el-col>
						<el-col :span="12">
							<el-button
								size="small"
								type="primary"
								class="submit-btn"
								@click="submit"
								:loading="saving"
							>
								登录
							</el-button>
						</el-col>
					</el-row>
				</div>
			</transition>
		</el-form>
	</div>
</template>
<script>
import { appEnv } from "@/config/env";
import { uniqBy } from "@/utils";
import { validate } from "@/utils/validate";
import * as dd from "dingtalk-jsapi";
let isDev = appEnv == "dev";
export default {
	data() {
		return {
			form: {
				mobile: isDev ? "" : "",
				password: isDev ? "" : "",
				user_id: isDev ? 0 : ""
			},
			rules: {
				mobile: [
					{ required: true, message: "请输入用户名" },
					{ pattern: validate.mobile, message: "格式不正确" }
				],
				password: [
					{ required: true, message: "请输入密码" },
					{ min: 6, max: 16, message: "密码长度应为6-16位" }
				],
				user_id: [{ required: true, message: "请选择集团" }]
			},
			groupList: [],
			isNext: false,
			saving: false,
			isDingding: false,
			isPwdLogin: true,
			returnCode: "",
			userMobile: "",
			ddLoading: false,
			ddConfigInfo: {},
			appkey: ""
		};
	},
	mounted() {
		this.isDingding = dd.env.platform === "notInDingTalk" ? false : true;
		const url = new URL(location.href);
		console.log("url", url);
		this.appkey = url.hostname; // 获取 appKey 的值

		if (this.isDingding) {
			if (!this.appkey) return this.$message.error("请联系开发者配置appkey");
			this.getDdConfig();
		}
	},
	methods: {
		async getDdConfig() {
			let res = await this.$service.public.dingConfig({ key: this.appkey });
			this.ddConfigInfo = res;
		},
		async nextStep() {
			this.isPwdLogin = false;
			if (!this.isNext) {
				// 这个是点击获取集团
				console.log("this.form", this.form);
				this.saving = true;
				const { mobile } = this.form;
				const list = await this.$store
					.dispatch("common/getGroupList", { mobile })
					.done(() => {
						this.saving = false;
					});
				this.isNext = true;
				let groupList = uniqBy(list, "user_id");
				this.groupList = groupList;
				groupList.length > 0 && (this.form.user_id = groupList[0].user_id);
				return;
			}
			this.saving = true;
		},
		async submit() {
			if (this.isDingding && this.isPwdLogin) {
				this.dingdingSubmit();
			} else {
				this.$refs.form.validate(async (valid, errors) => {
					this.showFormErr(errors);
					if (!valid) return;
					if (!this.isNext) {
						// 这个是点击获取集团
						console.log("this.form", this.form);
						this.saving = true;
						const { mobile } = this.form;
						const list = await this.$store
							.dispatch("common/getGroupList", { mobile })
							.done(() => {
								this.saving = false;
							});
						this.isNext = true;
						let groupList = uniqBy(list, "user_id");
						this.groupList = groupList;
						groupList.length > 0 && (this.form.user_id = groupList[0].user_id);
						return;
					}
					this.saving = true;
					// 登录;
					await this.$store.dispatch("selectUserLogin", this.form).done(() => {
						this.saving = false;
					});
					// 用户信息;
					// await this.$store.dispatch("userInfo");
					// 权限菜单;
					this.$router.push("/");
				});
			}
		},
		async dingdingLogin() {
			this.isPwdLogin = true;
			if (dd.env.platform === "notInDingTalk") {
				alert("请在钉钉客户端中打开此页面");
			} else {
				this.ddLoading = true;
				dd.requestAuthCode({
					...this.ddConfigInfo,
					onSuccess: async result => {
						try {
							let data = await this.$service.public.getGroupListByDt({
								code: result.code,
								key: this.appkey
							});
							this.userMobile = data.mobile;
							this.returnCode = data.code;
							let groupList = uniqBy(data.groupList, "user_id");
							this.groupList = groupList;
							groupList.length > 0 && (this.form.user_id = groupList[0].user_id);
							this.isDingding = true;
							this.isNext = true;
							this.ddLoading = false;
						} catch (err) {
							console.error("获取 authCode 失败:", err);
							this.ddLoading = false;
						}
					},
					onFail: err => {
						alert("调用失败", err);
						this.ddLoading = false;
					}
				});
				return;
				// console.log("authCode:", ddCode);
			}
		},
		async dingdingSubmit() {
			// 登录;
			let params = {
				code: this.returnCode,
				mobile: this.userMobile,
				user_id: this.form.user_id,
				key: this.appkey
			};
			try {
				await this.$store.dispatch("ddLogin", params).done(() => {
					this.saving = false;
					this.$router.push("/");
				});
			} catch (err) {
				// 用户信息;
				// await this.$store.dispatch("userInfo");
				// 权限菜单;
			}
		}
	}
};
</script>
<style lang="scss" scoped>
.account-form {
	box-sizing: border-box;
	padding: 40px;
}

.logo {
	height: 60px;
	margin-bottom: 30px;
}

.submit-btn {
	width: 100%;
}

/* ::v-deep {
	.el-form-item__label {
		font-size: 16px;
	}
} */
</style>
